﻿using HCService.Client;
using HCService.MsgHandler.SubHandler;
using HCService.Service;
using System;
using System.Collections.Generic;
using System.Text;

namespace HCService.MsgHandler
{

	public class PackHandlerCenter
	{
		private static PackHandlerCenter m_instan;
		public static PackHandlerCenter Instance { 
			get {
				if (m_instan == null)
					m_instan = new PackHandlerCenter();
				return m_instan;
			}
		}

		public delegate void PackHandle(IClient client, Pack pack);
		Dictionary<string, PackHandle> mapHandle;

		public PackHandlerCenter()
		{
			mapHandle = new Dictionary<string, PackHandle>();

			new ClientDisconnetHandler(this);
			new ClientRequestRes(this);
			new ClientAccountVerifyReq(this);
			new ClientRequestUser(this);
		}

		public void RegisterPackHandle(string key, PackHandle handle)
		{
			if (this.mapHandle.ContainsKey(key))
				Console.WriteLine("重复添加包处理方法");
			this.mapHandle.Add(key, handle);
		}

		public void UnRegisterPackHandle(string key)
		{
			if (this.mapHandle.ContainsKey(key))
				this.mapHandle.Remove(key);
		}

		public void Handle(IClient client, Pack pack)
		{
			try
			{
				var scuss = pack.Build();
				if (scuss)
				{
					//PackHandle handle = null;
					this.mapHandle.TryGetValue(pack.HandleTag, out PackHandle handle);
					if (null == handle)
						Console.WriteLine("不能处理");
					else
						handle.Invoke(client, pack);
				}
			}
			catch (Exception exp)
			{
				Console.WriteLine(exp.StackTrace);
			}	
		}
	
		public void Handle_out(IClient client, Pack pack)
		{
			var scuss = pack.Build();
			if (scuss)
			{
				if(mapHandle.TryGetValue(pack.HandleTag, out var handle))
				{
					handle?.Invoke(client, pack);
				}
			}
		}
	}
}
